/*
 * Copyright 2007, 2008 Tiberiumlabs
 *
 * This file is part of Tiberiumlabs Shards.
 *
 * Tiberiumlabs Shards is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Tiberiumlabs Shards is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.tiberiumlabs.screenshot;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import javax.swing.JComponent;

/**
 *
 * @author <a href="paranoid.tiberiumlabs@gmail.com">Paranoid</a>
 */
public class ImageComponent extends JComponent {

    private BufferedImage image;

    @Override
    public int getHeight() {
        if (image == null) {
            return 120;
        }
        return super.getHeight();
    }

    @Override
    public int getWidth() {
        if (image == null) {
            return 160;
        }
        return super.getWidth();
    }

    private Dimension preferredSize = new Dimension(320, 240);

    @Override
    public Dimension getPreferredSize() {
        return preferredSize;
    }

    @Override
    protected void paintComponent(Graphics g) {
        if (image != null) {

            double currentWidth = getWidth();
            double currentHeight = getHeight();

            double imageWidth = image.getWidth();
            double imageHeight = image.getHeight();

            double widthShape = imageWidth/currentWidth;
            double heightShape = imageHeight/currentHeight;

            double shape = Math.max(widthShape, heightShape);

            int width = (int)(imageWidth/shape);
            int height = (int)(imageHeight/shape);

            int x = (getWidth() - width)/2;

            Image resized = image.getScaledInstance(width, height, Image.SCALE_SMOOTH);
            g.drawImage(resized, x, 0, width, height, null);

        }
        else {

            g.fillRect(0, 0, 160, 120);

        }
    }

    public BufferedImage getImage() {
        return image;
    }

    public void setImage(BufferedImage image) {
        this.image = image;
    }

}
